/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.ieslaferreria.creditsintesis.logicgame.statemachineimpl;

import edu.ieslaferreria.creditsintesis.logicgame.StateMachine;
import edu.ieslaferreria.creditsintesis.logicgame.actions.StateChangedEvent;
import edu.ieslaferreria.creditsintesis.logicgame.actions.StateListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

/**
 *Maquina de estados que devuelve el siguiente estado segun el estado en el que este y
 * el activador que le manden.
 * @author Administrador
 */
public class GenericStateMachine implements StateMachine{
    public HashMap<Integer, LinkedList<StateListener>> listenerList =
                            new HashMap<Integer, LinkedList<StateListener>>();
    public int[][] stateMatrix;
    int state;

    public GenericStateMachine(){
    }

    public GenericStateMachine(boolean createBasicStates){
        if(createBasicStates){
            stateMatrix = new int[][] {{0, 0, 0, 0, 0, 0, 0}};
        }

    }

    public int getState(){
        return this.state;
    }

    public void setState(int activator){
        int oldState = this.state;
        int newState = this.stateMatrix[this.state][activator];
        System.out.println("Actual Estado" + this.state);
        System.out.println("nuevo Estado" + newState);
        System.out.println("Activador" + activator);
        this.state= newState;
        if(listenerList.containsKey(newState)){
            StateChangedEvent event = createEvent(oldState, newState);
            for(Iterator<StateListener> iter=listenerList.get(newState).iterator(); iter.hasNext(); ){
                iter.next().onChangeState(event);
            }
        }
    }

    public void addListener(int state, StateListener listener) {
        LinkedList list = null;
        if(listenerList.containsKey(state)){
            list = listenerList.get(state);
        }else{
            list = new LinkedList();
            listenerList.put(state, list);
        }
        list.add(listener);
    }

    public void removeListener(int state, StateListener listener) {
        if(listenerList.containsKey(state)){
            listenerList.remove(listener);
        }
    }

    protected StateChangedEvent createEvent(int oldState, int newState){
        return new StateChangedEvent(this.state, newState,null);
    }
}
